package cn.wecloud.im.multiplayervideodemo.http

import cn.wecloud.im.multiplayervideodemo.App
import cn.wecloud.im.multiplayervideodemo.BuildConfig
import cn.wecloud.im.multiplayervideodemo.utils.AppSharePre
import com.facebook.stetho.okhttp3.StethoInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


object RetrofitManager {

    val commonService: CommonService by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        getRetrofit(App.HTTP_URL).create(CommonService::class.java)
    }

    val liveMeetService: LiveMeetService by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        getRetrofit(App.LIVE_URL).create(LiveMeetService::class.java)
    }

    private fun getRetrofit(baseUrl: String): Retrofit {
        // 获取retrofit的实例
        return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getOkHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }

    private fun getOkHttpClient(): OkHttpClient {
        //头部拦截器
        val headersInterceptor = Interceptor { chain ->
            val original: Request = chain.request()
            val request: Request = original.newBuilder()
                .header("token", AppSharePre.getToken())
                .method(original.method, original.body)
                .build()
            chain.proceed(request)
        }

        val builder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            builder.addNetworkInterceptor(StethoInterceptor())
        }
        return builder
                .addInterceptor(headersInterceptor)
                .connectTimeout(30L, TimeUnit.SECONDS)
                .readTimeout(30L, TimeUnit.SECONDS)
                .writeTimeout(30L, TimeUnit.SECONDS)
                .build()
    }

}
